/**
 * 
 */
(function(w, d) {
    'use strict';
    if (typeof w.modejs === 'undefined') {
        w.modejs = {
            mode: 'anymode',
            changeMode: changeMode,
            functions: {
                disable: function(el) {
                    el.setAttribute('disabled', true);
                },
                enable: function(el) {
                    el.removeAttribute('disabled');
                },
                hide: function(el) {
                    el.original.hide = getComputedStyle(el).display;
                    el.style.display = 'none';
                },
                remove: function(el) {
                    el.parentNode.removeChild(el);
                },
                show: function(el) {
                    el.style.display = el.original.hide;
                }
            }
        };
    }

    function changeMode(data) {
        var attr = '', els = [];

        if (d.readyState === 'complete') {
            els = d.querySelectorAll('*[data-mode]')

            for (var i = 0, elsLength = els.length; i < elsLength; i += 1) {
                attr = _getElMode(els[i])[modejs.mode];

                if (typeof attr !== 'undefined') {
                    for (var j = 0, attrLength = attr.length; j < attrLength; j += 1) {
                        (function() {
                            modejs.functions[attr[j]](els[i]);
                        }());
                    }
                }
            }
        }
    }

    function initMode(e) {
        var els = d.querySelectorAll('*[data-mode]');

        for (var i = 0, elsLength = els.length; i < elsLength; i += 1) {
            if (typeof els[i].original === 'undefined')
                els[i].original = {};

            if (els[i].nodeName === 'BUTTON') {
                els[i].addEventListener('click', function(e) {
                    var attr = _getElMode(this)[modejs.mode];

                    for (var j = 0, attrLength = attr.length; j < attrLength; j += 1) {
                        if (attr[j] === 'hide' || attr[j] === 'disable') {
                            e.stopImmediatePropagation();

                            return false;
                        }
                    }
                });
            }
        }

        if (modejs.mode !== 'anymode') {
            changeMode();
        }
    }

    // Util functions
    function _getElMode(el) {
        return JSON.parse(el.getAttribute('data-mode').replace(/'/g, '"'));
    }

    w.addEventListener('load', initMode);
}(window, document));